import React, { Component } from 'react'
import ComSon from './ComSon'
class ComFather extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      msg: 'hello',
      age: 18,
      aaa: '',
      isShow: true
    }
  }
  hasChild = true
  transferMsg(msg) {
    this.setState({
      aaa: msg
    }, () => {
      console.log(this.state.aaa);
    });
  }
  old() {
    this.setState({
      age: 200
    })
  }
  showHello() {
    console.log('showHello:hello');
  }
  // 1. componentWillMount
  componentWillMount() {
    console.log('componentWillMount');
    console.log('我可以发请求');
    console.log('this.state.msg:', this.state.msg);
    this.showHello();
    console.log('componentWillMount');
  }
  // 3. componentDidMount
  componentDidMount() {
    console.log('componentDidMount');
    console.log(this.state.msg);
    this.showHello();
    console.log('componentDidMount');
  }
  // 更新期
  shouldComponentUpdate(nextProps, nextState) {
    // 数据变化后，需要判断是否更新dom，要返回一个布尔值
    console.log('父组件：', nextProps);
    console.log('父组件：', nextState);
    // 年龄差值超过5岁就更新，否则不更新
    return true
    // if (Math.abs(nextState.age - this.state.age) > 5) {
    //   return true
    // } else {
    //   return false
    // }
  }
  // 组件即将更新
  componentWillUpdate(nextProps, nextState) {
    console.log('componentWillUpdate');
    console.log(nextProps);
    console.log(nextState);
    console.log('componentWillUpdate');
  }
  // 组件更新完成
  componentDidUpdate(preProps, preState) {
    console.log('componentDidUpdate');
    console.log(preProps);
    console.log(preState);
    console.log('componentDidUpdate');
  }
  // 切换子组件的显示隐藏
  toggle() {
    this.setState({
      isShow: !this.state.isShow
    },()=> {
      console.log(this.state.isShow);
    })
  }
  render() {
    console.log('2.render');
    let com;
    if (this.state.isShow) {
      com = <ComSon info="111" age="20"/>;
    } else {
      com = <div>无</div>;
    }
    return (<div>
        {/* <p>我是父组件</p>
        <p>子组件传过来的值:{this.state.aaa}</p>
        <p>当前年龄：{this.state.age}</p>
        <button onClick={() => this.old()}>age+2</button> */}
      <button onClick={()=> this.toggle()}>toggle</button>
      {/* <hr /> */}
      {/* {this.state.isShow? <ComSon /> : ''} */}
        {com}
      {/* <hr />
      <p>生命周期共有三个状态：初始化、更新期、销毁期</p> */}
    </div>)
  }
}
export default ComFather